package org.example.myleet.rosalind.kmer;

import org.example.myleet.rosalind.utils.FastaReader;

import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        String path = solution.getClass().getResource("").getPath() + "example.txt";
        solution.printTetraMerMatrix(FastaReader.parseFastaFromFile(path).get(0).getSequence());
    }

    public void printTetraMerMatrix(String sequence) {
        int n = 4 * 4 * 4 * 4;
        List<String> tetras = new ArrayList<>(n);
        Map<String, Integer> tetraMerMapIndex = new HashMap<>(n);
        StringBuilder tetra = new StringBuilder();
        char[] alphabet = new char[]{'A', 'C', 'G', 'T'};
        for (int w = 0; w < 4; ++w) {
            tetra.append(alphabet[w]);
            for (int x = 0; x < 4; ++x) {
                tetra.append(alphabet[x]);
                for (int y = 0; y < 4; ++y) {
                    tetra.append(alphabet[y]);
                    for (int z = 0; z < 4; ++z) {
                        tetra.append(alphabet[z]);
                        String tetraMer = new String(tetra);
                        tetras.add(tetraMer);
                        tetra.deleteCharAt(tetra.length() - 1);
                    }
                    tetra.deleteCharAt(tetra.length() - 1);
                }
                tetra.deleteCharAt(tetra.length() - 1);
            }
            tetra.deleteCharAt(tetra.length() - 1);
        }
        tetras.sort(String::compareTo);
        for (int j = 0; j < tetras.size(); ++j) {
            tetraMerMapIndex.put(tetras.get(j), j);
        }
        int i = 0;
        int[] matrix = new int[n];
        Map<String, Integer> tetraMerMapAppearance = new HashMap<>(n);
        StringBuilder sb = new StringBuilder();
        for (int j = 0; j < 3; ++j) {
            sb.append(sequence.charAt(i++));
        }
        while (i < sequence.length()) {
            sb.append(sequence.charAt(i++));
            Integer idx = tetraMerMapIndex.get(sb.toString());
            if (null == idx) {
                throw new RuntimeException("Tetra-mer not found! " + sb);
            }
            ++matrix[idx];
            sb.deleteCharAt(0);
        }
        StringBuilder res = new StringBuilder();
        for (int j = 0; j < matrix.length; ++j) {
            res.append(matrix[j]).append(' ');
        }
        res.deleteCharAt(res.length() - 1);
        System.out.println(res);
    }
}
